/*******************************************************************************
 * Copyright 2011 WaTho
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package de.wathoserver.android.dragoid.activity.singlebuilding;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import de.wathoserver.android.dragoid.R;
import de.wathoserver.android.dragoid.api.Building;
import de.wathoserver.android.dragoid.api.BuildingMaterial;
import de.wathoserver.android.dragoid.api.DragoApi;
import de.wathoserver.android.dragoid.api.DragoStore;
import de.wathoserver.android.dragoid.api.StockItem.STOCK_TYPE;

/**
 * Zeigt den Materialbedarf eines Gebäudes an
 * 
 * @author watho
 * 
 */
public class SingleBuildingRessourcesActivity extends ListActivity {

	Building building;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onResume() {
		super.onResume();
		reload();
	}

	public void reload() {
		Intent parentIntent = getIntent();
		int pos = parentIntent.getIntExtra(Building.COL_POSITION, -1);
		building = DragoStore.getDragoStore().getBuildings().get(pos);
		setListAdapter(new MaterialBaseAdapter(this));
	}

	/**
	 * Controller für die Abbildung eines {@link BuildingMaterial}-Datensatzes
	 * auf einen Listeneintrag.
	 * 
	 * @author watho
	 * 
	 */
	private class MaterialBaseAdapter extends BaseAdapter {

		LayoutInflater inlfater;

		public MaterialBaseAdapter(Context context) {
			inlfater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return building.getMaterial().size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			BuildingMaterial bm = building.getMaterial().get(position);
			SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(SingleBuildingRessourcesActivity.this);
			String hoursStr = prefs.getString(
					"prefs_singlebuilding_add_material", "12");
			int hours = 12;
			try {
				hours = Integer.parseInt(hoursStr);
			} catch (NumberFormatException e) {
			}
			ViewHolder holder;
			if (convertView == null) {
				// Erstelle neue View und Viewholder
				convertView = inlfater.inflate(
						R.layout.singlebuilding_material_row, null);
				holder = new ViewHolder();
				holder.needs = (TextView) convertView
						.findViewById(R.id.singlebuilding_material_needs);
				holder.has = (TextView) convertView
						.findViewById(R.id.singlebuilding_material_has);
				holder.value = (EditText) convertView
						.findViewById(R.id.singlebuilding_material_value);
				holder.transfer = (Button) convertView
						.findViewById(R.id.singlebuilding_material_transfer);
				holder.transfer24 = (Button) convertView
						.findViewById(R.id.singlebuilding_material_do_24);
				holder.transfer24.setTag(bm);
				holder.transfer24.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						try {
							BuildingMaterial bm = (BuildingMaterial) v.getTag();
							DragoApi.getApi().transferMaterial(
									building.getPosition(), bm.getInc24(),
									bm.getStockType());
							reload();
						} catch (NumberFormatException e) {
						} catch (IllegalAccessException e) {
						}
					}
				});
				holder.transferSetting = (Button) convertView
						.findViewById(R.id.singlebuilding_material_do_setting);
				holder.transferSetting.setTag(bm);
				holder.transferSetting
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								try {
									SharedPreferences prefs = PreferenceManager
											.getDefaultSharedPreferences(SingleBuildingRessourcesActivity.this);
									String hoursStr = prefs
											.getString(
													"prefs_singlebuilding_add_material",
													"12");
									int hours = 12;
									BuildingMaterial bm = (BuildingMaterial) v
											.getTag();
									hours = Integer.parseInt(hoursStr);
									DragoApi.getApi().transferMaterial(
											building.getPosition(),
											bm.getIncHours(hours),
											bm.getStockType());
									reload();
								} catch (NumberFormatException e) {
								} catch (IllegalAccessException e) {
								}
							}
						});
				holder.withdraw = (Button) convertView
						.findViewById(R.id.singlebuilding_material_do_withdraw);
				holder.withdraw.setTag(bm);
				holder.withdraw.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						BuildingMaterial bm = (BuildingMaterial) v.getTag();
						try {
							DragoApi.getApi().getBackMaterial(
									building.getPosition(), bm.getStockType());
							reload();
						} catch (IllegalAccessException e) {
						}
					}
				});
				holder.value.setTag(bm.getStockType());
				// Menge der vorhanden Materialien
				// Wir hängen das Textfeld an den Button, damit wir im Listener
				// darauf zugreifen können.
				holder.transfer.setTag(holder.value);
				holder.transfer.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						TextView value = (TextView) v.getTag();
						try {
							DragoApi.getApi()
									.transferMaterial(
											building.getPosition(),
											Integer.parseInt(value.getText()
													.toString()),
											(STOCK_TYPE) value.getTag());
							reload();
						} catch (NumberFormatException e) {
						} catch (IllegalAccessException e) {
						}
					}
				});
				convertView.setTag(holder);
			} else {
				// verwende alten viewholder
				holder = (ViewHolder) convertView.getTag();
			}
			// Updates
			holder.needs.setText(String.format(
					"Benötigt %s %s pro h (%s am Tag)", bm.getNeeds(),
					bm.getStockType(), bm.getNeeds() * 24));
			holder.has.setText(String.format("Es befinden sich %s %s vor Ort",
					bm.getHas(), bm.getStockType()));
			holder.value.setText(String.valueOf(bm.getValue()));
			holder.transferSetting.setText(String.format("Für %sh\n%s %s",
					hours, bm.getIncHours(hours), bm.getStockType()));
			holder.transferSetting.setEnabled(bm.getIncHours(hours) > 0
					&& bm.getValue() >= bm.getIncHours(hours));
			holder.transfer24.setText(String.format("Für 24h\n%s %s",
					bm.getInc24(), bm.getStockType()));
			holder.transfer24.setEnabled(bm.getInc24() > 0
					&& bm.getValue() >= bm.getInc24());
			return convertView;
		}
	}

	static class ViewHolder {
		TextView needs;
		TextView has;
		EditText value;
		Button transfer;
		Button withdraw;
		Button transfer24;
		Button transferSetting;
	}
}
